--[[
-- @Author:      feilong
-- @DateTime:    2019-10-30 23:05:48
-- @Description: 日记记录
-- log文件按进程名按天生成
]]

local lfs = require "lfs"
local maxsize = 50 *1024*1024 --文件最大M，超过会分割

local MessageHandler = class("MessageHandler")

function MessageHandler:ctor()
    self.file = nil --文件句柄
    self.server_name = g.getenv("server_name") --节点名
    self.suffix = ".log" --文件后缀
    self.date = self:getDate()
    self.file_name = self.server_name.."_"..self.date --文件名
    self.path = "/home/logs/"
    -- self.date_path = self.path .. self.date .."/"
    lfs.mkdir(self.path)
    -- lfs.mkdir(self.date_path)
    self:register()
end

--注册本服务里的消息
function MessageHandler:register()
    --print("i am logger register!")
    g.dispatch:register("save_data", handler(self, self.saveData))
end

function MessageHandler:getDate( ... )
    return os.date("%Y_%m_%d",os.time())
end

--打开一个文件， 但不关闭
function MessageHandler:checkFile()
    -- local date = self:getDate()
    -- if self.date ~= date then 
    --     self.date = date
    --     self.date_path = self.path .. self.date .."/"
    --     lfs.mkdir(self.date_path)
    --     if self.file then 
    --         self.file:close()
    --         self.file = nil
    --     end
    -- end
    if self.file then
        return
    end
    local file_name = self.path .. self.file_name .. self.suffix
    self.file = io.open(file_name, "a+")
    if not self.file then
        error("log file cant open!!!!")
    end
end

--保存到文件
function MessageHandler:saveData(msg)
    -- print("logger saveData", msg)
    if not msg and not next(msg) then
        return
    end
    self:checkFile()
    if not self.file then
        print("error: logger saveData!")
        return
    end

    local data = msg.."\n"
    self.file:write(data)
    self.file:flush()
    local file_size = self.file:seek("end")
    if file_size >= maxsize then
        --分割文件
        local sub_time = os.date("%H_%M_%S",os.time())
        local file_name = self.date_path .. self.file_name .. self.suffix
        local rename = self.date_path .. self.file_name .."_"..sub_time .. self.suffix
        self.file:close()
        self.file = nil
        os.rename(file_name, rename)
    end
end


return MessageHandler